package com.speily.cloud.mall.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.speily.cloud.account.service.AccountService;
import com.speily.cloud.order.service.OrderService;
import com.speily.cloud.storage.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * ShoppingController
 *
 * @author : SPL
 * @since : 2021-04-20 14:05
 **/
@RestController
@RequestMapping("/shopping")
@Slf4j
public class ShoppingController {

    @DubboReference
    private AccountService accountService;
    @DubboReference
    private OrderService orderService;
    @DubboReference
    private StorageService storageService;

    /**
     * 下单
     *
     * @return
     */
    @PostMapping("/buy")
    @GlobalTransactional
    @SentinelResource("buy")
    public Object order() {

        //1、扣除余额
        //2、减库存
        //3、生成订单
        log.info("下单 buy");

        accountService.decreaseAccount("111");
        orderService.createOrder();
        storageService.decreaseStorage();

        return new HashMap<>();
    }

    /**
     * sentinel 测试
     *
     * @return
     */
    @PostMapping("/sentinel")
//    @SentinelResource(value = "sentinel", blockHandler = "exceptionHandler")
    //使用此注解，需手动实现兜底操作，参考https://www.jianshu.com/p/04941d066db0
    public Object sentinel() {

        //1、扣除余额
        //2、减库存
        //3、生成订单
        return "hello sentinel";
    }

}
